package com.example.speechrepeat;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;


public class MainActivity extends Activity implements OnClickListener{
	
	private static final int VOICE_RECOGNITION_REQUEST_CODE=1234;
	
	private ListView mList;
	private Button speakButton;

	private Bundle activities;
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_main);
		speakButton = (Button) findViewById(R.id.speech_btn);
		mList = (ListView) findViewById(R.id.word_list);
		
		//detecet whether audio recognition is available
		PackageManager pm = getPackageManager();
		List<ResolveInfo> acitivties = pm.queryIntentActivities(
				new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH),0);
		if(activities.size()!=0){
			speakButton.setOnClickListener(this);
		}else{
			speakButton.setEnabled(false);
			speakButton.setText("Audio Recognition is not available");
		}
	}

	/**
	 * handle the click on the start recognition button
	 */
	public void onClick(View v) {
		if (v.getId() == R.id.speech_btn) {
			startVoiceRecognitionActivity();
		}
	}

	/**
	 * Instruct the app to listen for user speech input
	 */
	private void startVoiceRecognitionActivity() {
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"Speech Recognition");
		startActivityForResult(intent,VOICE_RECOGNITION_REQUEST_CODE);
	}

	/**
	 * Handle the results from the recognition activity
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
			//Fill the list view with the strings the recognizer thought it could have heard
			ArrayList<String> matches = data
					.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			mList.setAdapter(new ArrayAdapter<String>(this, R.layout.word,
					matches));
		}
		super.onActivityResult(requestCode,resultCode,data);
	}
}
